package event;

import java.util.Date;
import java.util.List;
import java.io.Serializable;

import org.hibernate.Session;

import util.HibernateUtil;

public class EventManager {

    static String   name = "b";
    public static void main(String[] args) {

        EventManager mgr = new EventManager();

            Long eventId = (Long)mgr.createAndStroeEvent("My Event", new Date());
            Long personId = (Long)mgr.createAndStroePerson(12,"han","liang");


            List events = mgr.listEvent();
                for(int i= 0; i<events.size();i++){
                    Event theEvent = (Event)events.get(i);
                    System.out.println("Event-->"+theEvent.getTitle()+" | " + "Date-->"+theEvent.getDate());
                }
            mgr.addPersonToEvent(personId,eventId);
        System.out.println("add person "+personId + "to event "+eventId);
            
        HibernateUtil.getSessionFactory().close();

	}

	private Serializable createAndStroeEvent(String title, Date theDate){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		Event theEvent = new Event();
		theEvent.setTitle(title);
		theEvent.setDate(theDate);

	   return session.save(theEvent);
	}
    private Serializable createAndStroePerson(int age , String firstName,String lastName){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Person thePerson = new Person();
        thePerson.setAge(age);
        thePerson.setFirstName(firstName);
        thePerson.setLastName(lastName);
        return session.save(thePerson);
        //session.getTransaction().commit();

    }

    private List listEvent(){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List result = session.createQuery("from Event").list();
        session.getTransaction().commit();
        return result;
    }
    private void addPersonToEvent(Long personId,Long eventId){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Person aPerson = (Person)session.load(Person.class,personId);
        Event anEvent = (Event)session.load(Event.class,eventId);
        aPerson.getEvents().add(anEvent);
        session.getTransaction().commit();
    }

}
